<template>
  <n-config-provider id="body w-full" :theme-overrides="naiveTheme">
    <module-header name="app" value="/patient" is-telescreen />

    <main-content>
      <n-space v-if="state" vertical class="w-3/5">
        <div class="text-xl text-white">按日期筛选</div>
        <div>
          <n-date-picker v-model:value="pStartTime" placeholder="选择日期" @update:value="searchByDateTime" />
        </div>
        <n-data-table size="large"
                      :columns="columns"
                      :data="viewData"
                      :pagination="pagination"
                      :single-line="false"
        />
      </n-space>
      <div v-else class="w-3/5 flex justify-center relative" style="box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.5);
                  background-color: white;overflow: auto;border-radius: 5px;"
      >
        <n-button type="primary" class="mt-2 right-8 absolute" @click="returnH">返回</n-button>
        <n-space vertical class="mt-12">
          <n-steps vertical :current="(current as number)" :status="currentStatus">
            <n-step v-for="(item,i) in ProcessRef.Process" :key="i" :title="item.iname" style="max-width: 50vw;">
              <strong>医生:</strong> {{ item.name }}
              <strong>地点:</strong> {{ item.therapyAddress }}
              <strong>日期:</strong> {{ item.startTime.split('T')[0] }}
              <strong>完成时间:</strong> {{ item.finishTime }} 分钟
              <strong>间隔时间:</strong> {{ item.intervalTime }} 分钟
            </n-step>
          </n-steps>
        </n-space>
      </div>
    </main-content>
  </n-config-provider>
</template>

<script lang="ts" setup>
import { ref, h, onMounted } from 'vue'
import { naiveTheme } from '../../shared/theme/naive_theme'
import { NConfigProvider, NDataTable, NSpace, NButton, NDatePicker,
  DataTableColumns, StepsProps, NSteps, NStep } from 'naive-ui'
import { axiosReq } from '../../shared/client/axios'
import { actErr } from '../../shared/client/interact'
import ModuleHeader from '../../components/common/module_header.vue'
import MainContent from '../../components/common/main_content.vue'
import { transStatus, reqGetHistoryByDate, reqGetHistory, timestampToDateTime } from './patient.def'

const state = ref<number>(1)
const pStartTime = ref<any>(null)

type RowData = {
  key: number
  startTime: string
}

const createColumns = ({
  sendMail
}: {
  sendMail: (rowData: RowData) => void
}): DataTableColumns<RowData> => {
  return [
    {
      title: '治疗日期',
      key: 'startTime'
    },
    {
      title: '查看详情',
      key: 'actions',
      render (row) {
        return h(
          NButton,
          {
            size: 'small',
            onClick: () => sendMail(row)
          },
          { default: () => '更多' }
        )
      }
    }
  ]
}

const columns = createColumns({
  sendMail (rowData) {
    state.value = 0
    const data = ProcessAll.value.ProcessList.filter(process => {
      if(process.prId == rowData.key)
        return process
    })
    ProcessRef.value.Process = data

    for(let i = 0;i < ProcessRef.value.Process.length;i++) {
      currentStatus.value = transStatus(ProcessRef.value.Process[i].status)
      if(ProcessRef.value.Process[i].status == 3 && i != ProcessRef.value.Process.length - 1) {
        next()
      } else {
        return
      }
    }
  }
})

const ProcessRef = ref<any>({
  Process:[{
    did:1,
    finishTime:10,
    gender:false,
    id:0,
    iid:1,
    iname:'项目1',
    intervalTime:30,
    name:'张三',
    num:1,
    phone:'13800138000',
    pid:0,
    prId:6,
    report:true,
    startTime:'2024-06-01T15:38:34',
    status:2,
    therapyAddress:'Address 1'
  }]
})

const ProcessAll = ref<any>({})

const viewData = ref([])

const pagination = {
  pageSize: 10
}


const currentRef = ref<number | null>(1)
const currentStatus = ref<StepsProps['status']>('wait')
const current = currentRef

onMounted(async () => {
  if(!import.meta.env.SSR) {
    const res = await reqGetHistory(axiosReq)
    if(res.code != 200) {
      actErr(res.message)
      return
    }
    ProcessAll.value = res.data

    viewData.value = ProcessAll.value.PrIdList.map(prId => {
      const process = ProcessAll.value.ProcessList.find(p => p.prId === prId)
      return { key: process.prId, startTime: process.startTime.split('T')[0] }
    })
  }
})

function next () {
  if (currentRef.value === null) currentRef.value = 1
  else if (currentRef.value >= ProcessRef.value.Process.length) currentRef.value = null
  else currentRef.value = currentRef.value + 1
}

async function searchByDateTime() {
  console.log(pStartTime.value)
  console.log(Date.now())
  const res = await reqGetHistoryByDate(axiosReq, timestampToDateTime(pStartTime.value))
  if(res.code != 200) {
    actErr(res.message)
    return
  }
  ProcessRef.value = res.data

  if(ProcessRef.value.Process.length == 0) {
    actErr('没有数据')
    return
  }

  state.value = 0
  for(let i = 0;i < ProcessRef.value.Process.length;i++) {
    currentStatus.value = transStatus(ProcessRef.value.Process[i].status)
    if(ProcessRef.value.Process[i].status == 3 && i != ProcessRef.value.Process.length - 1) {
      next()
    } else {
      return
    }
  }

}

function returnH() {
  state.value = 1
  pStartTime.value = null
}
</script>

<style>
@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';
</style>
